// API 基础URL
const API_BASE = 'http://localhost:8080/api';

// DOM 元素
const userForm = document.getElementById('userForm');
const nameInput = document.getElementById('nameInput');
const emailInput = document.getElementById('emailInput');
const usersList = document.getElementById('usersList');
const refreshBtn = document.getElementById('refreshBtn');

// 页面加载时获取用户列表
document.addEventListener('DOMContentLoaded', loadUsers);

// 表单提交事件
userForm.addEventListener('submit', async (e) => {
    e.preventDefault();

    const userData = {
        name: nameInput.value,
        email: emailInput.value
    };

    try {
        const response = await fetch(`${API_BASE}/users`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(userData)
        });

        if (response.ok) {
            showMessage('用户添加成功！', 'success');
            nameInput.value = '';
            emailInput.value = '';
            loadUsers(); // 刷新列表
        } else {
            const error = await response.text();
            showMessage(`添加失败: ${error}`, 'error');
        }
    } catch (error) {
        showMessage('网络错误，请检查服务器是否运行', 'error');
    }
});

// 刷新按钮事件
refreshBtn.addEventListener('click', loadUsers);

// 加载用户列表
async function loadUsers() {
    try {
        usersList.innerHTML = '<div class="loading">加载中...</div>';

        const response = await fetch(`${API_BASE}/users`);
        if (!response.ok) {
            throw new Error('获取用户列表失败');
        }

        const users = await response.json();
        displayUsers(users);
    } catch (error) {
        usersList.innerHTML = `
            <div class="error">
                无法加载用户列表: ${error.message}
                <br>请确保后端服务器正在运行在 http://localhost:8080
            </div>
        `;
    }
}

// 显示用户列表
function displayUsers(users) {
    if (users.length === 0) {
        usersList.innerHTML = '<div class="loading">暂无用户数据</div>';
        return;
    }

    usersList.innerHTML = users.map(user => `
        <div class="user-card">
            <h3>${user.name}</h3>
            <p>📧 ${user.email}</p>
            <p>🆔 ID: ${user.id}</p>
        </div>
    `).join('');
}

// 显示消息
function showMessage(message, type) {
    const messageDiv = document.createElement('div');
    messageDiv.className = type;
    messageDiv.textContent = message;

    // 插入到表单前面
    userForm.parentNode.insertBefore(messageDiv, userForm);

    // 3秒后自动消失
    setTimeout(() => {
        messageDiv.remove();
    }, 3000);
}